import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';

import { TioConnection } from '@/plugins/websocket';
import useAuthStore from '@/stores/auth.store';
import { hasPermission } from '@/utils/haveIntersection';
import { hideFullLoading, showFullLoading } from '@/utils/nProgress';
import { filterTree } from '@/utils/tree';
// import routesAdmin from '@/views/admin-page';
import routerHomePage from '@/views/home-page';
import routerLoginPage from '@/views/login-page';

const routes: RouteRecordRaw[] = [...routerHomePage, ...routerLoginPage];

const initRouter = () => {
  const authStore = useAuthStore();
  const result: RouteRecordRaw[] = [
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/error-page/ErrorPage.vue'),
      meta: {
        title: '404',
        requiresBack: true,
      },
    },
  ];
  const children = filterTree(
    routes,
    (route) => !hasPermission(authStore.permissions, (route?.meta?.permissions || []) as string[]),
  );
  if (authStore.roles.includes('admin')) {
    // children.push(...routesAdmin);
  }

  if (children.length === 0) {
    //
  } else {
    result.push({
      path: '',
      redirect: children[0].path,
    });
  }

  result.push({
    path: '/',
    component: () => import('@/components/MumeiLayout.vue'),
    children,
  });

  const router = createRouter({
    history: createWebHistory(import.meta.env.VITE_BASE_URL),
    routes: result,
  });

  router.afterEach(() => {
    hideFullLoading();
  });
  router.beforeEach(() => {
    // eslint-disable-next-line no-new
    new TioConnection('ws://124.222.6.60:8800/');

    showFullLoading();
    return true;
  });
  return router;
};

export default initRouter;
